package com.biz.primus.ms.payment.channel.allinpay.req;

import com.biz.primus.ms.payment.channel.wechat.exceptions.PaymentException;
import com.biz.primus.ms.payment.channel.wechat.lang.SimpleHttpClient;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * AllInPayRequestBase
 *
 * @author JKLiues
 * @date 2017年11月10日
 */
@Getter
@Setter
public abstract class AllInPayRequestBase {


    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    protected SimpleHttpClient getSimpleHttpClient() {
        return new SimpleHttpClient();
    }

    /**
     * 获取接口地址
     *
     * @return String
     */
    protected abstract String getApiUrl();

    /**
     * 获取需要签名的字段
     *
     * @return Collection<String>
     */
    public abstract Collection<String> getSignParams();

    protected String buildUrl(String url, Map<String, Object> map) {
        if (MapUtils.isEmpty(map)) {
            throw new PaymentException("缺少参数");
        }
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        sb.append("?");
        List<String> kvPair = Lists.newArrayList();
        for (String key : map.keySet()) {
            Object o = map.get(key);
            if (Objects.nonNull(o) && StringUtils.isNotBlank(String.valueOf(o))) {
                kvPair.add(String.format("%s=%s", key, String.valueOf(o)));
            }
        }
        String join = StringUtils.join(kvPair, "&");
        sb.append(join);
        return sb.toString();
    }
}